package com.joseph.websocket.util;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.joseph.websocket.bean.UserInfo;
import com.joseph.websocket.bean.UserSession;
import jodd.time.TimeUtil;
import org.apache.dubbo.rpc.RpcContext;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.*;

public final class JedisUtil {

    private static Gson gson = new GsonBuilder().create();

    private JedisUtil() {
    }

    private static JedisPool jedisPool;
    private static int maxtotal;
    private static int maxwaitmillis;
    private static String host;
    private static int port;

    /*读取jedis.properties配置文件*/
    static {
        ResourceBundle rb = ResourceBundle.getBundle("jedis");
        maxtotal = Integer.parseInt(rb.getString("maxtotal"));
        maxwaitmillis = Integer.parseInt(rb.getString("maxwaitmillis"));
        host = rb.getString("host");
        port = Integer.parseInt(rb.getString("port"));
    }

    /*创建连接池*/
    static {
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxTotal(maxtotal);
        jedisPoolConfig.setMaxWaitMillis(maxwaitmillis);
        jedisPoolConfig.setMaxIdle(50);
        jedisPool = new JedisPool(jedisPoolConfig, host, port, 3000, "EXOvkbhh");
    }

    /*获取jedis*/
    public static Jedis getJedis() {
        return jedisPool.getResource();
    }

    /*关闭Jedis*/
    public static void close(Jedis jedis) {
        if (jedis != null) {
            jedis.disconnect();
        }
    }

    public static void main(String[] args) {
        long s = System.currentTimeMillis();
        UserInfo userInfo = new UserInfo();
        userInfo.setUserId("0001");
        Map map = new HashMap();
        UserSession userSession = new UserSession();
        userSession.setSessionType("0");
        userSession.setStoreCode("ST0001");
        userSession.setSessionId("RG00001");
        map.put("ST0001", userSession);
        userInfo.setSessions(map);
        //getJedis().set(userInfo.getUserId(), JSON.toJSONString(userInfo));
        //System.out.println(getJedis().get("0001"));
        for (int i = 0; i < 100; i++) {
           // gson.toJson(userInfo);
            JSON.toJSONString(userInfo);
        }
        System.out.println(System.currentTimeMillis() - s);
    }
}